<?php

if (!file_exists($app_root . '/images/.htaccess')) {
	mkdir($app_root . '/images', 0755, true);
	file_put_contents(
		$app_root . '/images/.htaccess',
		  "<FilesMatch \"\.jpg$\">\n"
		. "Header set Cache-Control \"max-age=290304000, public\"\n"
		. "Header set Pragma \"\"\n"
		. "Header set Expires \"Fri, 1 Jan 2100 00:00:00 GMT\"\n"
		. "</FilesMatch>\n"
	);
}

require 'image_functions.php';
$jpeg_quality    = isset($env['image']['jpeg_quality']) ? $env['image']['jpeg_quality'] : 60;
$png_compression = isset($env['image']['png_compression']) ? $env['image']['png_compression'] : 5;
$max_width       = isset($env['image']['max_width']) ? $env['image']['max_width'] : false;
$max_height      = isset($env['image']['max_height']) ? $env['image']['max_height'] : false;
$max_dimension   = isset($env['image']['max_dimension']) ? $env['image']['max_dimension'] : false;

if ($max_width  == false) $max_width  = $max_dimension;
if ($max_height == false) $max_height = $max_dimension;

$www_path   = '/' . join('/', $path);
$cache_file = $app_root . $www_path;

array_pop($path); // discard filename

$image_id = array_pop($path);
if (ctype_digit($image_id)) {
	
	$image = $db->fetchRow("SELECT * FROM cms_images WHERE id=? AND site_id=?", array($image_id, $site['id']));
	
	if (!in_array($image['mime_type'], array('image/jpeg', 'image/gif', 'image/png'))) {
		$image['mime_type'] = 'image/jpeg';
	}
	
	header("Content-type: {$image['mime_type']}");
	header("Content-disposition: inline; filename={$image['filename']}");
	header('Expires: ' . date('r', strtotime('+ 5 years')));
	header('Cache-Control: max-age=' . (strtotime('+ 5 years') - time()));
	header('Pragma: ');
	header('Last-modified: ' . date('r', strtotime($image['created'])));
	header('ETag: "image-' . $image['id'] . '"');
	
	if (file_exists($cache_file)) {
		readfile($cache_file);
		exit;
	} else {
		
		$gd = imagecreatefromstring($image['data']);

		$commands = array_slice($path, 1);
		foreach($commands as $command) {
			$command = split(':', $command);
			if ($command[0] == 'rc' and ctype_digit($command[1]) and ctype_digit($command[2])) $gd = resizeandcrop($gd, $command[1], $command[2]);
			elseif ($command[0] == 'rp' and ctype_digit($command[1]) and ctype_digit($command[2])) $gd = resizeandpad($gd, $command[1], $command[2], isset($command[3]) ? $command[3] : 'FFFFFF');
			elseif ($command[0] == 'r' and ctype_digit($command[1]) and ctype_digit($command[2])) $gd = resize($gd, $command[1], $command[2]);
			elseif ($command[0] == 'w' and ctype_digit($command[1])) $gd = resizetowidth($gd, $command[1]);
			elseif ($command[0] == 'h' and ctype_digit($command[1])) $gd = resizetoheight($gd, $command[1]);
			elseif ($command[0] == 'm' and ctype_digit($command[1])) $gd = resizetomax($gd, $command[1]);
			elseif ($command[0] == 'ds') $gd = dropshadow($gd, $command[1], isset($command[2]) ? $command[2] : 'FFFFFF');
			elseif ($command[0] == 'p' and ctype_digit($command[1]) and ctype_digit($command[2]) and ctype_digit($command[3]) and ctype_digit($command[4])) $gd = pad($gd, $command[1], $command[2], $command[3], $command[4], isset($command[5]) ? $command[5] : 'FFFFFF');
			elseif ($command[0] == 'q') $jpeg_quality = $command[1];
			elseif ($command[0] == 'pl') $placeholder = $command[1];
		}
		
		if (isset($placeholder)) {
			// placeholder image
			$gd = imagecreate(imagesx($gd), imagesy($gd));
			$background_color = fromhex($placeholder, $gd);
		}
		
		if (($max_height and (imagesy($gd) > $max_height)) or ($max_width and (imagesx($gd) > $max_width))) {
			$logger->info('Image dimensions exceeded: ' . $cache_file);
			header("HTTP/1.0 403 Forbidden");
			header("Content-type: text/html");
			echo "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n";
			echo "<html><head>\n";
			echo "<title>403 Forbidden</title>\n";
			echo "</head><body>\n";
			echo "<h1>Forbidden</h1>\n";
			echo "<p>The maximum allowed image dimension has been exceeded.</p>\n";
			echo "<hr>\n";
			echo "<address>".$_SERVER['SERVER_SOFTWARE']." at ".$_SERVER['SERVER_NAME']."</address>\n";
			echo "</body></html>\n";
			exit;
		} else {
			@mkdir(dirname($cache_file), 0755, true);
			if ($image['mime_type'] == 'image/gif' or isset($placeholder)) {
				imagegif($gd, $cache_file);
				imagegif($gd);
				touch($cache_file, strtotime($image['created']));
			}
			elseif ($image['mime_type'] == 'image/jpeg') {
				imagejpeg($gd, $cache_file, $jpeg_quality);
				imagejpeg($gd, null, $jpeg_quality);
				touch($cache_file, strtotime($image['created']));
			}
			elseif ($image['mime_type'] == 'image/png') {
				imagepng($gd, $cache_file, $png_compression);
				imagepng($gd, null, $png_compression);
				touch($cache_file, strtotime($image['created']));
			}
			if (isset($env['cdn']['cloudfiles']['username']) and isset($env['cdn']['cloudfiles']['apikey'])) {
				cloudfiles_insert($www_path, file_get_contents($cache_file));
				unlink($cache_file);
			}
			
		}
		exit;
	}
	
} else {
	echo "Invalid ID";
}



